package weifei.wx.community.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

public class AdminerTokenInterceptor implements HandlerInterceptor
{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception
    {
        var token = request.getHeader("access_token");
        if (token == null) {
            PrintWriter out = response.getWriter();
            out.println("没有权限");
            return false;
        }


        var adminer_id = JWT.decode(token).getClaim("adminer_id").asInt();
        if (adminer_id == null)
        {
            PrintWriter out = response.getWriter();
            out.println("无效的token");
            return false;
        }

//
//        var adminer = this.adminerService.getAdminerByID(adminer_id);
//        if (adminer == null)
//        {
//            PrintWriter out = response.getWriter();
//            out.println("不存在的管理员");
//            return false;
//        }

        try {
            JWTVerifier jwt_verifier = JWT
                    .require(Algorithm.HMAC256(adminer_id.toString()))
                    .build();
            jwt_verifier.verify(token);
        }
        catch (JWTVerificationException e) {
            PrintWriter out = response.getWriter();
            out.println("token验证失败");
            return false;
        }


        return true;
    }
}



